// 请求页面
import request from '@/utils/request';
import type {
  LoginRequest,
  LoginResponse,
  ConfirmBrandResponse,
  Brand
} from "..//types/userType";
import type {ApiResponse, FileUploadResponse, MyResponse, ProductResource} from "..//types/commonTypes";
import type {
  BaseResponse,
  Product,
  AttributeProduct,
  PageResult
} from "..//types/productTypes";
import type {CategoryTreeResponse} from "@/common/types/category";
import type {OrderListResult} from "@/common/types/orderTypes";
import type { DiscountInfo, DiscountQueryParams } from "@/common/types/discountTypes";
// 登录接口
export async function loginStore(data: LoginRequest): Promise<LoginResponse> {
  const response = await request.post<LoginResponse>('/user/loginStore', data);
  return response.data; // 返回后端返回的数据
}

// 确认品牌接口
export async function confirmBrand(brandId:never, userId: never ): Promise<ConfirmBrandResponse> {
  // 构造请求参数
  const params = new URLSearchParams();
  params.append('brandId', userId);
  params.append('userId', brandId);
  // 发送请求
  const response = await request.post<ConfirmBrandResponse>('/user/confirmBrand', params);
  return response.data; // 返回后端返回的数据
}

export function getBrandById() {
  return request.get<{ state: boolean, msg: string }>("/user/getStoreInfo");
}
export function updateBrand(brand:Brand) {
  return request.put<{ state: boolean, msg: string }>("api/brand/updateBrand", brand);
}
export function sendSms(phone: string) {
  return request.post<{ state: boolean, msg: string }>("user/sendSms", phone);
}
export function GetBrandByUserId() {
  return request.get<{ state: boolean, msg: string }>("user/storeInfo");
}

// 商品分页查询
export async function getProductListByBrandId(
  params: {
    current?: number;
    size?: number;
  }
): Promise<ApiResponse<PageResult<Product>>> {
  return request.get('product/list/brand', { params });
}
// 品牌商品多条件查询
export async function getBrandProductsWithConditions(
  params: {
    current?: number;
    size?: number;
    productName?: string;
    productId?: number;
    categoryId?: number;
    minPrice?: number;
    maxPrice?: number;
    updateTime?: string; // 使用 ISO 格式时间字符串
  }
): Promise<ApiResponse<PageResult<Product>>> {
  return request.get('product/list/brand/condition', { params });
}
// 新增商品（带属性）
export async function createProduct(
  product: Product
): Promise<BaseResponse<void>> {
  return request.post('product/add', product);
}

// 修改商品基本信息
export async function updateProduct(
  product: Product
): Promise<BaseResponse<void>> {
  return request.put('product/credit', product);
}

// 获取商品属性列表
export async function getAttributes(
  productId: number
): Promise<ApiResponse<AttributeProduct[]>> {
  return request.get(`attribute/${productId}`);
}

// 创建
export async function saveAttribute(
  attr: AttributeProduct
): Promise<BaseResponse<void>> {
  return request.post(`attribute/creat`, attr);
}
//更新属性
export async function putAttribute(
  attribute:AttributeProduct
): Promise<ApiResponse<void>> {
  return request.put(`attribute/update`,attribute);
}
//获取分类
export async function getCategory():Promise<CategoryTreeResponse>{
  return request.get('/category/tree');
}
export const uploadFile = async (formData: FormData): Promise<ApiResponse<FileUploadResponse>> => {
  return request.post('/upload', formData);
}
// 获取商品资源列表
export async function getProductResourcesByProductId(
  productId: number
): Promise<ApiResponse<ProductResource[]>> {
  return request.get(`productResource/${productId}`);
}
// 新增商品资源
export async function createProductResource(
  resource: ProductResource
): Promise<BaseResponse<void>> {
  return request.post('productResource/create', resource);
}
// 删除商品资源
export async function deleteProductResource(
  id: number
): Promise<BaseResponse<void>> {
  return request.delete(`productResource/delete/${id}`);
}
//订单
export async function getBrandOrders(
  params: {  // 正确传递查询参数
    status:number,
    current:number,
    size:number
  }
): Promise<ApiResponse<MyResponse<never>>>{
  return request.get(`order/list/brand`, {params});
}
export async function getOrderProducts(
  orderId: number
): Promise<ApiResponse<OrderListResult[]>> {
  return request.get(`orderProduct/${orderId}`);
}

export async function updateOrderStatus(
    orderId:number,
    newStatus: number
): Promise<ApiResponse<MyResponse<never>>>{
  return request.put(`/order/status/brand?orderId=${orderId}&newStatus=${newStatus}`);
}


// 优惠券相关API
export const DiscountAPI = {
  // 创建店铺优惠券
  createBrand: (data: DiscountInfo) =>
    request.post<ApiResponse<MyResponse<never>>>('/api/discountInfo/brand/create', data),

  // 下架优惠券
  deactivateBrand: (discountId: number) =>
    request.put<ApiResponse<MyResponse<never>>>(`/api/discountInfo/brand/${discountId}/deactivate`),

  replenish: (discountId: number, amount: number) =>
    request.put(`/api/discountInfo/${discountId}/replenish`, null, {
      params: { discountNum: amount } // 参数名与后端@RequestParam完全匹配
    }),
  // 分页查询
  getList: (params: DiscountQueryParams) =>
    request.get<MyResponse<PageResult<DiscountInfo>>>('/api/discountInfo/list', { params }),

  // 更新优惠券
  update: (data: Partial<DiscountInfo>) =>
    request.put<ApiResponse<MyResponse<never>>>(`/api/discountInfo/edit`, data)
};
// 获取指定品牌在指定时间范围内的订单数
export const getOrderCountByBrandIdAndTimeRange = async (
  startTime: string | null,
  endTime: string | null
) => {
  const response = await request.get(`api/brand/order/orderCount/timeRange`, {
    params: {
      startTime,
      endTime
    }
  });
  return response.data;
};

// 获取指定品牌在指定时间范围内的成交金额
export const getTotalAmountByBrandIdAndTimeRange = async (
  startTime: string | null,
  endTime: string | null
) => {
  const response = await request.get(`api/brand/order/totalAmount/timeRange`, {
    params: {
      startTime,
      endTime
    }
  });
  return response.data;
};

// 用户相关类型定义
interface User {
  userId: number
  username: string
  phone: string
  email?: string
  gender?: number
  isDisabled?: number
  avatarUrl?: string
}

interface UserQueryParams {
  username?: string
  isDisabled?: number
  phone?: string
  gender?: number
  current: number
  size: number
}

// 用户管理API
export const UserAPI = {
  // 创建用户
  create: (data: User) =>
    request.post('/user/create', data),

  // 更新用户信息
  update: (data: Partial<User>) =>
    request.put('/user/update', data),

  // 禁用用户
  disable: (userId: number) =>
    request.put(`/user/disable/${userId}`),

  // 启用用户
  enable: (userId: number) =>
    request.put(`/user/open/${userId}`),

  // 分页查询用户
  getList: (params: UserQueryParams) =>
    request.get('/user/list', { params })
}
